const fs = require("fs");
const path = require('path')
const getImgSize = require('image-size')

const source = path.join(__dirname, '../', '../', 'pics');

module.exports = function getPics(req, res) {
    const {lockList, imgSource, imgNum, friendList} = req.query;
    let count = imgNum;
    let pre = lockList ? lockList.length : 0;
    let data = [];
    let dir = source;

    if (imgSource === 'public' || imgSource === 'mixed') {
        dir = source + '/public';
        try {
            data = fs.readdirSync(dir);
            data.forEach((v, i) => {
                data[i] = path.join(path.basename(dir), v);
            });
        } catch (err) {
            return res.cc(err)
        }
    }

    if (imgSource === 'private' || imgSource === 'mixed') {
        if (!req.auth) return res.cc('尚未登录')
        dir = path.join(source, req.auth.username);
        try {
            let personalData = fs.readdirSync(dir);
            personalData.forEach((v, i) => {
                data[i] = path.join(path.basename(dir), v);
            })
            data = personalData.concat(data);
            friendList.forEach((friend) => {
                dir = path.join(source, friend);
                personalData = fs.readdirSync(dir);
                personalData.forEach((v, i) => {
                    data[i] = path.join(path.basename(dir), v);
                })
            })
        } catch (err) {
            return res.cc(err)
        }
    }

    if (data.length === 0) return res.cc('该合集下没有任何图片，请切换图片来源重试')

    if (lockList) {
        const lockImgs = new Set(req.query['lockList']);
        let c = 0;
        data.forEach((d,i) => {
            if (lockImgs.has(d)) {
                const subLen = data.length - c;
                [data[subLen-1], data[i]] = [data[i], data[subLen-1]];
                lockImgs.delete(d);
                c++;
            }
        });
        // 在修改图片源目录后，原锁定图片可能不存在于当前目录中，需要额外添加
        if (lockImgs.size) {
            lockImgs.forEach(img => data.push(img))
        }
    }

    for (let c=pre; c<count; c++) {
        const subLen = data.length - c;
        const randomIndex = Math.floor(Math.random() * subLen);
        [data[subLen-1], data[randomIndex]] = [data[randomIndex], data[subLen-1]];
    }

    const urlList = data.slice(-count);
    const sizeList = [];
    (async () => {
        for (let i=0; i<urlList.length; i++) {
            try {
                const size = await getImgSize(path.join(source, urlList[i]));
                sizeList.push({width: size.width, height: size.height});
            } catch (err) {
                return res.cc(err)
            }
        }
        res.cc({urlList, sizeList}, 0);
    })()
}